package edu.suda.basic.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * @author Bill Tu(tujiyue/iwtxokhtd) May 27, 2011[10:04:20 PM]
 * 
 */
public class NiangXiPi
{
	private static final String	PROTOCOL	= "pop3";
	private static final String	HOST		= "pop.sina.com";
	private static final String	USER		= "summerpulse2012@sina.com";
	private static final String	PASS		= "20056768";

	private static Session getMailSession()
	{
		Properties props = new Properties();
		props.put("mail.store.protocol", PROTOCOL);
		props.put("mail.pop3.host", HOST);

		Session session = Session.getDefaultInstance(props);
		return session;
	}

	private static void receiveEmail() throws MessagingException, IOException
	{
		Store store = getMailSession().getStore();
		store.connect(HOST, USER, PASS);

		Folder receiveFolder = store.getFolder("inbox");// 对于POP3协议此参数值只能是inbox
		receiveFolder.open(Folder.READ_WRITE);// 设置收件夹打开后的读写权限

		int messageCount = receiveFolder.getMessageCount();
		System.out.println("总共拥有邮件数：" + messageCount);

		if (messageCount > 0)
		{
			Message[] messages = receiveFolder.getMessages();// 得到所有的邮件
			for (int i = 0; i < messages.length; i++)
			{
				Message msg = messages[i];
				System.out.println("第" + (i + 1) + "封邮件的主题为：" + msg.getSubject() + " ,其发送人地址为：" + msg.getFrom()[0]);
				System.out.println("您是否要阅读此邮件？若要请输入yes,否则就输入no:");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				String input = br.readLine();
				if (input != null && !"".equals(input) && "yes".equals(input.trim()))
				{
					msg.writeTo(System.out);// 直接输出到控制台,当然也输出到文件中。
				}
			}
		}
		receiveFolder.close(true);// 关闭邮件夹对象
		store.close();// 断开连接

	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws MessagingException
	 */
	public static void main(String[] args) throws MessagingException, IOException
	{
		receiveEmail();
	}
}
